/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "ChrRacesDbc.h"

#include "NativeFile.h"

namespace PQGameCore
{
	const std::string ChrRacesDbc::PATH="dbc/ChrRaces.dbc";

	ChrRacesDbc::ChrRacesDbc()
	{
		//_dbc=SWOWArchive.openDbcFile(PATH);
		PQEngine::FileBase* file=new PQEngine::NativeFile(PATH);
		_dbc=new WOWDbcFile(file);
		delete file;
		assert(_dbc);
	}

	ChrRacesDbc& ChrRacesDbc::getSingleton()
	{
		static ChrRacesDbc inst;
		return inst;
	}

	ChrRacesRecord* ChrRacesDbc::getRecord(std::string name)
	{
		if(!_dbc){
			return 0;
		}

		std::transform(name.begin(), name.end(),name.begin(), ::toupper);
		RecordList::iterator it= _records.find(name);
		if(it!=_records.end()){
			return it->second;
		}

		int cnt=_dbc->getRecordCount();
		for(int i=0;i<cnt;i++){
			
			std::string recordName=_dbc->getStringField(i,WOW_DBC_CHR_RACE_NAME_FIELD);//v3.1
			std::transform(recordName.begin(), recordName.end(),recordName.begin(), ::toupper);

			if(recordName==name){
				ChrRacesRecord* record=new ChrRacesRecord();
				//pointer into dbc file buffer is better,but some field we not need,so
				record->raceId= _dbc->getUIntField(i,0);
				record->maleModelId=_dbc->getUIntField(i,4);
				record->femaleModelId=_dbc->getUIntField(i,5);
				record->shortName=_dbc->getStringField(i,6);
				record->name=_dbc->getStringField(i,WOW_DBC_CHR_RACE_NAME_FIELD);//v
				//record->fullName=_dbc->getStringField(i,14);
				record->geotype1=_dbc->getStringField(i,65);
				//record->geotype2=_dbc->getStringField(i,66);
				//record->geotype3=_dbc->getStringField(i,67);

				_records.insert(RecordList::value_type(name,record));
				return record;
			}
		}
		//not find
		return 0;
	}

	int ChrRacesDbc::getRecordCount(Ogre::uint race, Ogre::uint gender, Ogre::uint type, Ogre::uint section, Ogre::uint npc)
	{
		if(!_dbc){
			return 0;
		}
		int n = 0;
		int cnt=_dbc->getRecordCount();
		for(int i=0;i<cnt;i++){
			Ogre::uint recordRace=_dbc->getUIntField(i,1);
			Ogre::uint recordGender=_dbc->getUIntField(i,2);
			Ogre::uint recordType=_dbc->getUIntField(i,3);
			Ogre::uint recordSection=_dbc->getUIntField(i,8);

			if (recordRace==race && recordGender==gender && recordType==type && recordSection==section ) {
				n++;
			}
		}
		return n;
	}


	
}

